﻿
using FineUIMvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BoYuan.DBServices;
using BoYuan.FineUIMvcWeb.Controllers;
using BoYuan.Framework.Uitility;
using DtCms.Common;

namespace BoYuan.FineUIMvcWeb.Areas.Admin.Controllers
{
    public partial class wmfileController : BaseController
    {
        #region ListPage
        // GET: Admin/wmfile
        public ActionResult Index()
        {
            ViewBag.wmid = int.Parse(Request["wmid"]);
            var mo = DBServices.DB_Base.GetModel<Entity.waterMarkObj>(ViewBag.wmid);
            ViewBag.img = string.IsNullOrEmpty(mo.pic2)? string.Empty : mo.pic2;
            

            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Grid1_PageIndexChanged(FormCollection fc)
        {
            var db = DB_Base.Instance;
            int wmid = int.Parse(fc["f_wmid"]);
            //此处代码不能设置断点debug。
            var queryable = db.Queryable<BoYuan.Entity.wmfile>()
                .Where(p=>p.wmid==wmid)
                .OrderBy(p => p.id)
                .Select<BoYuan.Entity.wmfile>() ;

            var grid1 = UIHelper.Grid("Grid1");
            grid1.BindGrid(fc, "ddlPageSize", queryable);
            return UIHelper.Result();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Button_delete_Click(string ids)
        {
            var idList = Array.ConvertAll<string, int>(ids.Substring(1).Split(','), int.Parse);
            if (idList.Length == 0)
            {
                NotifyQuestion("请选择要删除的选中行！");
            }
            else
            {
                var db = DBServices.DB_Base.Instance;
                db.Deleteable<BoYuan.Entity.wmfile>(p => idList.Contains(p.id)).ExecuteCommand();
                AlertSuccess("删除成功！", false, "onGridBind()");
            }
            return UIHelper.Result();
        }
        #endregion

        #region AddPage

        public ActionResult Add()
        {
            if (int.TryParse(Request["id"],out int id))//编辑页面初始化
            {
                BoYuan.Entity.wmfile mo = DBServices.DB_Base.GetModel<BoYuan.Entity.wmfile>(id);

                if (mo.ispic)
                {
                    return Redirect("/admin/wmfile/AddPic?id="+ id);
                }

                ViewBag.wmid = mo.wmid;
                return View(mo);
            }

            ViewBag.wmid = int.Parse(Request["wmid"]);
            return View();//添加页面
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Button_save_OnClick(FormCollection fc)
        {
            bool isEdit = int.TryParse(fc["f_id"], out int id);

            BoYuan.Entity.wmfile mo = new BoYuan.Entity.wmfile();
            mo.title = fc["f_title"];
            mo.ispic = false;
            if (int.TryParse(fc["f_w"], out var wTempResult)) mo.w = Convert.ToInt32(fc["f_w"]);
           
            if (double.TryParse(fc["f_x"], out var xTempResult)) mo.x = Convert.ToInt32(fc["f_x"]);
            if (double.TryParse(fc["f_y"], out var yTempResult)) mo.y = Convert.ToInt32(fc["f_y"]);
            mo.wmid= Convert.ToInt32(fc["f_wmid"]); 


            if (!isEdit)//添加
            {

                if (DBServices.DB_Base.InsertModel(mo) > 0)
                {
                    AlertInfor("添加成功", true);
                }
                else
                {
                    NotifyError("添加失败");
                }
            }
            else//修改
            {
                int returnNum= DBServices.DB_Base.UpdateModels(mo, 
                           //注意更新字段是否对应，数量是否一致 
p => new {p.title,p.ispic,p.w,p.h,p.x,p.y,p.wmid},
                           //条件
                           p => p.id==id);
                if (returnNum>0)
                {
                    AlertInfor("修改成功", true);
                }
                else
                {
                    NotifyError("修改失败");
                }
            }
            return UIHelper.Result();
        }
        #endregion

        #region AddPic

        public ActionResult AddPic()
        {
            if (int.TryParse(Request["id"], out int id))//编辑页面初始化
            {
                BoYuan.Entity.wmfile mo = DBServices.DB_Base.GetModel<BoYuan.Entity.wmfile>(id);

                if (!mo.ispic)
                {
                    return Redirect("/admin/wmfile/Add?id=" + id);
                }
                ViewBag.wmid = mo.wmid;
                ViewBag.img = mo.title;
                return View(mo);
                
            }

            ViewBag.img = string.Empty;
            ViewBag.wmid = int.Parse(Request["wmid"]);
            return View();//添加页面
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Button_savePic_OnClick(FormCollection fc)
        {
            bool isEdit = int.TryParse(fc["f_id"], out int id);

            BoYuan.Entity.wmfile mo = new BoYuan.Entity.wmfile();
            mo.title = fc["f_img"];
            mo.ispic = true;
            if (int.TryParse(fc["f_w"], out var wTempResult)) mo.w = Convert.ToInt32(fc["f_w"]);
            if (int.TryParse(fc["f_h"], out var hTempResult)) mo.h = Convert.ToInt32(fc["f_h"]);
            if (double.TryParse(fc["f_x"], out var xTempResult)) mo.x = Convert.ToInt32(fc["f_x"]);
            if (double.TryParse(fc["f_y"], out var yTempResult)) mo.y = Convert.ToInt32(fc["f_y"]);
            if (byte.TryParse(fc["f_Transparency"], out var f_Transparency)) mo.Transparency = f_Transparency;

            if (!isEdit)//添加
            {
                mo.wmid = Convert.ToInt32(fc["f_wmid"]);

                if (DBServices.DB_Base.InsertModel(mo) > 0)
                {
                    AlertInfor("添加成功", true);
                }
                else
                {
                    NotifyError("添加失败");
                }
            }
            else//修改
            {
                int returnNum = DBServices.DB_Base.UpdateModels(mo,
//注意更新字段是否对应，数量是否一致 
                    p => new { p.title, p.ispic, p.w, p.h, p.x, p.y,p.Transparency},
                    //条件
                    p => p.id == id);
                if (returnNum > 0)
                {
                    AlertInfor("修改成功", true);
                }
                else
                {
                    NotifyError("修改失败");
                }
            }
            return UIHelper.Result();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult filePhoto_FileSelected(HttpPostedFileBase f_pic, FormCollection fc)
        {
            using (UploadFileCommand ufc = new UploadFileCommand(f_pic))
            {
                if (!ufc.UpLoadIMG())
                {
                    AlertError("上传图片错误:" + ufc.Error);
                }

                UIHelper.Image("f_img").ImageUrl(ufc.FileName_url);
            }

            UIHelper.FileUpload("f_pic").Reset();//重置表单
            return UIHelper.Result();
        }

        #endregion

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ShowPic(FormCollection fc)
        {
            int wmid = int.Parse(fc["f_wmid"]);

            var db = DBServices.DB_Base.Instance;

            var wmList= db.Queryable<Entity.wmfile>().Where(p => p.wmid == wmid).ToList();
            if (wmList == null || wmList.Count == 0)
            {
                AlertError("没有要生成水印信息");
                return UIHelper.Result();
            }

            var mo = DBServices.DB_Base.GetModel<Entity.waterMarkObj>(wmid);
            string basepic = mo.pic;
            string saveUrl = string.IsNullOrEmpty(mo.pic2)? UploadFileCommand.GetNewSaveFileUrl(): mo.pic2;

            //文字水印
            var txtList = wmList.Where(p => p.ispic == false).ToList();
            if (txtList != null && txtList.Count > 0)
            {
                List<ImageWaterMark.WaterMarkText> list = new List<ImageWaterMark.WaterMarkText>();

                foreach (var txt in txtList)
                {
                    list.Add(new ImageWaterMark.WaterMarkText() { X = (float)txt.x, Y = (float)txt.y, Text = txt.title });
                }


                //批量打印文字
                ImageWaterMark.AddImageText(basepic, saveUrl, 100, list);
            }

            //图片水印
            var picList = wmList.Where(p => p.ispic == true).ToList();
            if (picList != null && picList.Count > 0)
            {
                System.Drawing.Image tempImage = null;
                foreach (var pic in picList)
                {
                   tempImage = ImageWaterMark.PictureProcess(pic.title, (int)pic.w, (int)pic.h);
                   ImageWaterMark.AddImageSignPicByXY(saveUrl, saveUrl, tempImage, (int)pic.x, (int)pic.y, 100, pic.Transparency);
                }

                tempImage.Dispose();
            }

            var img = UIHelper.Image("f_img");
            img.ImageUrl(saveUrl+"?r="+DateTime.Now.ToString("ffff"));

            return UIHelper.Result();
        }


        
    }
}
